/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.wsapi.module.user.controller;

import com.wsapi.commons.vo.Page;
import com.wsapi.commons.vo.PageList;
import com.wsapi.module.user.dao.module.User;
import com.wsapi.module.user.service.UserManagementService;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Resource;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 用户管理
 *
 * @author yangyan <y.os@qq.com>
 */
@Controller
@RequestMapping("/management/user")
public class UserManagementController {

    @Resource
    private UserManagementService userManagementService;

    /**
     * 列表
     *
     * @param offset
     * @return
     */
    @RequestMapping("/list")
    @ResponseBody
    public Map<String, Object> list(Page.Offset offset) {
        Map<String, Object> map = new HashMap<String, Object>();
        PageList<User> roleList = userManagementService.findByPage(offset);
        map.put("success", true);
        map.put("userList", roleList);
        return map;
    }

    /**
     * 添加
     *
     * @param user
     * @return
     */
    @RequestMapping("/add")
    @ResponseBody
    @RequiresPermissions("USER:ADD")
    public Map<String, Object> add(User user) {
        Map<String, Object> map = new HashMap<>();
        userManagementService.addUser(user);
        map.put("success", true);
        return map;
    }

    /**
     * 修改
     *
     * @param user
     * @return
     */
    @RequestMapping("/update")
    @ResponseBody
    @RequiresPermissions("USER:EDIT")
    public Map<String, Object> update(User user) {
        Map<String, Object> map = new HashMap<>();
        userManagementService.updateUser(user);
        map.put("success", true);
        return map;
    }

    /**
     * 删除
     *
     * @param user
     * @return
     */
    @RequestMapping("/remove")
    @ResponseBody
    @RequiresPermissions("USER:REMOVE")
    public Map<String, Object> remove(User user) {
        Map<String, Object> map = new HashMap<>();
        userManagementService.removeUser(user);
        map.put("success", true);

        return map;
    }

    @InitBinder
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        dateFormat.setLenient(false);
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
    }
}
